# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import datetime
import logging
import json
from typing import List, Union

from tornado import gen

import coin.flow.topic_map as topic_map
from coin.base.param_util import to_list
from coin.exchange.base.ws.subscriber import WebsocketJsonSubscriberBase
from coin.exchange.quoinex_v2.ws.subscriber import parse_channel
from coin.exchange.quoinex_v2.kr_rest.product import QuoinexProduct
from coin.exchange.quoinex_v2.config import single_channel_group_symbol

VIEW_KEY = {
    "access_key":
        "1075952",
    "secret_key":
        "1bVfUOTPU7IdTfzxuDQSXZiv50budWwBpD3o4ydJfly1b0y+IGrIbbY6gIgbu5q6PENQ8hsZ+rVv+6IyvX1dUw==",
}


def _gen_auth_request():
  from liquidtap.utils import createJWT
  auth_token = createJWT(VIEW_KEY['access_key'], VIEW_KEY['secret_key'])
  auth_request = {
      'event': 'quoine:auth_request',
      'data': {
          'path': '/realtime', 'headers': {
              'X-Quoine-Auth': auth_token
          }
      }
  }
  return auth_request


class QuoinexSingleChannelSubscriber(WebsocketJsonSubscriberBase):
  def __init__(self,
               queue,
               group_id: str,
               worker_id: str,
               symbol: Union[List[str], str],
               close_callback=None,
               logger=None):
    super().__init__(close_callback, logger or logging.getLogger(__name__))
    self._symbol = to_list(symbol)
    assert len(self._symbol) == 1
    self._symbol = self._symbol[0]

    self._register_url('wss://tap.liquid.com/app/LiquidTapClient?rate_limit=15kb')
    self._publisher = None
    self._init_publisher(queue, group_id, worker_id)

  def _init_publisher(self, queue, group_id: str, worker_id: str):
    topic_depth = topic_map.search_topic_id('quoinex_ws_single_channel_depth_%s%s' %
                                            (group_id, worker_id))[0]
    topic_trade = topic_map.search_topic_id('quoinex_ws_single_channel_trade_%s%s' %
                                            (group_id, worker_id))[0]

    self._publisher = {
        'depth_single_channel': queue.get_writer(topic_id=topic_depth[1]),
        'trade': queue.get_writer(topic_id=topic_trade[1]),
    }

    self._enable_topic_event_publisher(queue,
                                       'quoinex_ws_topic_event', [topic_depth[0], topic_trade[0]])
    self._add_teardown_callback(self._teardown_publisher)

  @gen.coroutine
  def on_open(self):
    yield self._send_subscribe_request()
    super().on_open()

  @gen.coroutine
  def _send_subscribe_request(self):
    self._logger.debug('Subscribing %s' % self._symbol)
    yield self._ws.write_message(json.dumps(_gen_auth_request()))

    subscribe_depth_str = json.dumps({
        'event': 'pusher:subscribe',
        'data': {
            'channel': 'price_ladders_cash_%s' % self._symbol.lower(),
        }
    })
    yield self._ws.write_message(subscribe_depth_str)

    subscribe_trade_str = json.dumps({
        'event': 'pusher:subscribe',
        'data': {
            'channel': 'executions_cash_%s' % self._symbol.lower(),
        }
    })
    yield self._ws.write_message(subscribe_trade_str)

    yield gen.sleep(0.5)  # Sleep 0.5 second before next request

    self._publish_topic_event('START')
    self._logger.info('Subscribe done')

  def _teardown_publisher(self):
    if self._publisher:
      for _, publisher in self._publisher.items():
        publisher.close()
      self._publisher = None

  def on_message(self, timestamp: int, message: bytes):
    if self.stopped:
      return

    if 'channel' not in message:
      if 'event' in message and message['event'] == 'quoine:auth_failure':
        self._ioloop.add_timeout(datetime.timedelta(seconds=5), self._send_subscribe_request)
        self._logger.warning('Wait and retry: %s' % message)
        return
      self._logger.warning('Unknown message: %s' % message)
      return
    channel = message['channel']

    if 'event' not in message:
      self._logger.warning('Unknown message: %s' % message)
      return
    event = message['event']

    if event not in ['updated', 'created']:
      # Subscribe response.
      return

    type = parse_channel(channel)
    try:
      self._publisher[type].write(timestamp, message)
    except (KeyError, ValueError):
      self._logger.error('Unknown channel: %s' % message)


class QuoinexSingleChannelMultiSubscriberWrapper(object):
  BookFeedDisconnectWindowInNs = 2 * 60 * 1e9  # 2 mins

  def __init__(self,
               queue,
               group_id: str,
               worker_id: str,
               symbols: Union[List[str], str],
               close_callback=None,
               logger=None):
    assert group_id == "TBD"
    self._subscribers = []
    self._symbols = []
    for product in to_list(symbols):
      self._symbols.append(QuoinexProduct.FromStr(product).native_subscription_symbol)

    for symbol in self._symbols:
      group_id = None
      for k, v in single_channel_group_symbol.items():
        if symbol in v:
          group_id = k
      assert group_id is not None, (symbol, group_id)
      self._subscribers.append(
          QuoinexSingleChannelSubscriber(queue, group_id, worker_id, symbol, close_callback,
                                         logger))

  def subscribe(self):
    for subscriber in self._subscribers:
      subscriber.subscribe()

  def start(self, *args, **kwargs):
    for subscriber in self._subscribers:
      subscriber.start(*args, **kwargs)

  def stop(self, *args, **kwargs):
    for subscriber in self._subscribers:
      subscriber.stop(*args, **kwargs)
